package com.fary.config.property;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;

@Slf4j
public class CustomizeEnvironmentPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        CompositePropertySourceFactory compositePropertySourceFactory = new CompositePropertySourceFactory();
        try {
            System.out.println("postProcessEnvironment");
            for (int i = 0; i < 10; i++) {
                String moduleName = environment.getProperty("module[" + i + "]");
                if (StrUtil.isBlank(moduleName)) {
                    break;
                }
                String rootDir = System.getProperty("user.dir");
                String resolvedLocation = environment.resolveRequiredPlaceholders("file:/" + rootDir + "/" + moduleName + "/src/main/resources/application.yml");

                DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
                Resource resource = defaultResourceLoader.getResource(resolvedLocation);

                PropertySource<?> propertySource = compositePropertySourceFactory.createPropertySource(moduleName + ".yml", new EncodedResource(resource));
                environment.getPropertySources().addLast(propertySource);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
